package com.cserver.appapi.controller;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.cserver.appapi.model.TenantInfo;
import com.cserver.appapi.model.UserInfo;
import com.cserver.appapi.service.TenantInfoService;
import com.cserver.appapi.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.UUID;

@Controller
public class IndexController {

    @Value("${api-url}")
    private String APIURL;

    @GetMapping("/")
    public String index(ModelMap modelMap,HttpServletRequest request){

        HttpSession session = request.getSession();
        UserInfo userInfo= (UserInfo) session.getAttribute("USER");
        if(userInfo==null){//未登录
            modelMap.put("msg","未登录,请从正确入口登录");
            return "msg";
        }

        Integer usercount = userInfoService.countByTenantid(userInfo.getTenantid());
        modelMap.put("usercount",usercount);
        modelMap.put("userInfo",userInfo);


        return "index";
    }

    /**
     * 系统访问入口
     * @param sysid
     * @return
     */
    @GetMapping(value = "/login")
    public String login(String sysid, ModelMap modelMap, HttpServletRequest request){
        if(StringUtils.isEmpty(sysid)){
            modelMap.put("msg","租户id不能为空");
            return "msg";
        }
        TenantInfo tenantInfo = tenantInfoService.getTenantInfoById(sysid);
        if(tenantInfo==null){
            modelMap.put("msg","租户不存在");
            return "msg";
        }
        //获取本项目用户信息回调地址
        StringBuffer url = request.getRequestURL();
        String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append("/").toString();
        tempContextUrl=tempContextUrl+"/loginSuccess";
        //单点登录地址
        String ssourl=APIURL+"/sso/login?sysid="+sysid+"&redirecturl="+tempContextUrl;

        return "redirect:"+ssourl;
    }

    /**
     * 获取用户信息后的回调地址
     * @param info
     * @return
     */
    @GetMapping(value = "/loginSuccess")
    public String loginSuccess(String info,ModelMap modelMap, HttpServletRequest request){
        HttpSession session = request.getSession();
        UserInfo userInfo= (UserInfo) session.getAttribute("USER");
        if(userInfo!=null){//已经登录，不再登录
            return "redirect:/";
        }
        JSONObject jsonget = JSONObject.parseObject(info);
        jsonget.getBoolean("success");
        if(!jsonget.getBoolean("success")){//登录不成功
            modelMap.put("msg",jsonget.getString("msg"));
            return "msg";
        }
        userInfo = userInfoService.getUserInfoByUsername(jsonget.getString("username"));
        if(userInfo==null){
            modelMap.put("msg","用户不存在");
            return "msg";
        }
        //1.获取系统有效性
        String tenantid = userInfo.getTenantid();
        String body = HttpRequest.post(APIURL + "/api/getTenantInfo").header("sysid", tenantid).execute().body();
        System.out.println("getTenantInfo="+body);
        JSONObject jsonObject = JSONObject.parseObject(body);
        if(!jsonObject.getBoolean("success")){
            modelMap.put("msg","服务异常");
            return "msg";
        }
        if(!jsonObject.getBoolean("usable")){
            modelMap.put("msg","系统已过期");
            return "msg";
        }
        //2.用户登录成功日志
        jsonObject=new JSONObject();
        jsonObject.put("operation","查看");
        jsonObject.put("object","进入系统");
        jsonObject.put("data",userInfo.getUsername()+"进入系统");
        jsonObject.put("loginName",userInfo.getUsername());
        body=HttpRequest.post(APIURL + "/api/addLog").
                header("sysid", tenantid).
                header("Content-Type", "application/json;charset=UTF-8").
                body(jsonObject.toString()).execute().body();
        System.out.println("addLog="+body);
        //3.返回用户信息到页面
        session.setAttribute("USER",userInfo);


        return "redirect:/";
    }


    /**
     * 创建租户接口
     * @param jsonget
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/registTenant",produces = "application/json;charset=UTF-8")
    public JSONObject createUser(@RequestBody JSONObject jsonget,HttpServletRequest request){
        JSONObject jsonReturn = new JSONObject();
        String loginName=jsonget.getString("loginName");
        if(loginName==null){
            jsonReturn.put("success",false);
            jsonReturn.put("resultMessage","loginName不能为空");
            return jsonReturn;
        }
        String timeStamp=jsonget.getString("timeStamp");
        String mySign= SecureUtil.md5(loginName+timeStamp.charAt(3)+timeStamp.charAt(6)+timeStamp.charAt(9));

        if(!mySign.equalsIgnoreCase(jsonget.getString("sign"))){
            jsonReturn.put("success",false);
            jsonReturn.put("resultMessage","签名不合法");
            return jsonReturn;
        }

        String thirdAppid=jsonget.getString("thirdAppid");
        String thirdAppkey=jsonget.getString("thirdAppkey");
        //此处仅为举例
        if(!"testid".equalsIgnoreCase(thirdAppid)||!"testkey".equalsIgnoreCase(thirdAppkey)){
            jsonReturn.put("success",false);
            jsonReturn.put("resultMessage","凭证不合法");
            return jsonReturn;
        }
        String tenantid= UUID.randomUUID().toString();//用户绑定组织机构
        //注册租户
        TenantInfo tenantInfo = new TenantInfo();
        tenantInfo.setId(tenantid);
        //租户名称：取公司名称，公司为空，取用户账号
        tenantInfo.setTenantName(jsonget.getString("companyName")!=null?
                jsonget.getString("companyName"):
                jsonget.getString("loginName"));
        //注册用户
        UserInfo userInfo = new UserInfo();
        userInfo.setId(UUID.randomUUID().toString());
        userInfo.setTenantid(tenantid);
        userInfo.setUsername(jsonget.getString("loginName"));

        tenantInfoService.addTenantInfo(tenantInfo,userInfo);
        //获取本项目用户信息回调地址
        StringBuffer url = request.getRequestURL();
        String accessUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append("/").toString();

        jsonReturn.put("success",true);
        jsonReturn.put("resultMessage","创建系统成功");
        jsonReturn.put("sysid",tenantid);
        jsonReturn.put("accessurl",accessUrl);//访问地址

        return jsonReturn;
    }

    /**
     * 添加用户接口
     * @param userInfo
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/addUser",produces = "application/json;charset=UTF-8")
    public JSONObject addUser(UserInfo userInfo,HttpServletRequest request){
        JSONObject jsonObject = new JSONObject();
        HttpSession session = request.getSession();
        UserInfo nowUserInfo= (UserInfo) session.getAttribute("USER");
        //当前用户不能为空
        if(nowUserInfo==null){
            jsonObject.put("success",false);
            jsonObject.put("msg","非法请求");
            return jsonObject;
        }

        UserInfo userInfoDb = userInfoService.getUserInfoByUsername(userInfo.getUsername());
        if(userInfoDb!=null){
            jsonObject.put("success",false);
            jsonObject.put("msg","账号已经存在");
            return jsonObject;
        }
        TenantInfo tenantInfo = tenantInfoService.getTenantInfoById(nowUserInfo.getTenantid());
        jsonObject=new JSONObject();
        jsonObject.put("loginName",userInfo.getUsername());
        jsonObject.put("name","匿名");
        jsonObject.put("password","123456");
        jsonObject.put("company",tenantInfo.getTenantName());

        String body=HttpRequest.post(APIURL + "/api/registUser").
                header("sysid", nowUserInfo.getTenantid()).
                header("Content-Type", "application/json;charset=UTF-8").
                body(jsonObject.toString()).execute().body();
        jsonObject = JSONObject.parseObject(body);
        System.out.println("/api/registUser="+jsonObject.toString());
        if(!jsonObject.getBoolean("success")){
            jsonObject.put("success",false);
            jsonObject.put("msg",jsonObject.getString("resultMessage"));
            return jsonObject;
        }
        userInfo.setId(UUID.randomUUID().toString());
        userInfo.setTenantid(nowUserInfo.getTenantid());
        userInfoService.addUserInfo(userInfo);
        jsonObject.put("success",true);
        return jsonObject;
    }

    /**
     * 系统退出口
     * @param request
     * @return
     */
    @GetMapping(value = "/logout")
    public String logout(HttpServletRequest request,ModelMap modelMap){

        HttpSession session = request.getSession();
        UserInfo userInfo= (UserInfo) session.getAttribute("USER");

        if (userInfo==null){
            session.removeAttribute("USER");
            modelMap.put("msg","登出成功");
            return "msg";
        }
        //单点退出地址
        String ssourl=APIURL+"/sso/logout?sysid="+userInfo.getTenantid();

        session.removeAttribute("USER");
        return "redirect:"+ssourl;
    }

    @Autowired
    private TenantInfoService tenantInfoService;

    @Autowired
    private UserInfoService userInfoService;
}
